package com.wfy.common.aop;

import com.wfy.common.config.Global;
import com.wfy.common.entity.ResultGenerate;
import com.wfy.common.util.Logger;
import com.wfy.common.util.StringUtils;
import com.wfy.modules.sys.entity.ApiKey;
import com.wfy.modules.sys.service.ApiKeyService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: wangxindong
 * Date: 2017/3/11 Time: 20:52
 */
@SuppressWarnings("all")
@Order(1)
@Aspect
@Component
public class AccessControlAop {

    private static final Logger LOGGER = Logger.getLogger(AccessControlAop.class);

    @Resource
    private ApiKeyService apiKeyService;

    @Pointcut("execution(public * com.wfy.modules.openInterface.web..*(..))")
    public void aroundPointCut() {

    }


    @Around("aroundPointCut()")
    public Object setDataSource(ProceedingJoinPoint point) throws Throwable {
        RequestAttributes attr = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sa = (ServletRequestAttributes) attr;
        HttpServletRequest request = sa.getRequest();

        String tokenHeader = request.getHeader("token");

        if (StringUtils.isBlank(tokenHeader)) {
            return ResultGenerate.getResult(Global.INVALID_USER_KEY_MSG, Global.INVALID_USER_KEY_CODE);
        }

        ApiKey api = new ApiKey();
        api.setToken(tokenHeader);
        List<ApiKey> tmp = apiKeyService.getApiKey(api);

        if (null == tmp || tmp.size() == 0) {
            return ResultGenerate.getResult(Global.INVALID_USER_KEY_MSG, Global.INVALID_USER_KEY_CODE);
        }

        return point.proceed();
    }

    /**
     * 获取代理的方法的类名
     *
     * @param point
     * @return
     */
    private String getClassName(ProceedingJoinPoint point) {
        String name = point.getTarget().getClass().getSimpleName();
        return name;
    }

    /**
     * 获取当前运行的方法名称
     *
     * @param point
     * @return
     */
    private String getMethodName(ProceedingJoinPoint point) throws Exception {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        String methodName = method.getName();
        return methodName;
    }

}
